package com.amumu.netctoss.dao.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.amumu.netctoss.dao.CostDao;
import com.amumu.netctoss.entity.Cost;
@Repository
@Scope("prototype")

@SuppressWarnings("unchecked")
public class HibernateCostDao extends HibernateBaseDao implements CostDao{

	public void delete(int id) throws Exception {
		Cost cost = findById(id);
		getHibernateTemplate().delete(cost);
	}


	public List<Cost> findAll() throws Exception {
		return (List<Cost>) getHibernateTemplate().find("from Cost");
	}

	public List<Cost> findAll(int page,int size) throws Exception {
		String hql = "from Cost";
		return findByPage(page, size, hql, null);
	}

	public Cost findById(int id) {
		return (Cost) getHibernateTemplate().load(Cost.class, id);
	}

	public Cost findByName(String name) throws Exception {
		String hql = "from Cost where name=?";
		return (Cost) uniqueResult(hql, name);
		
		
	}

	public List<Cost> findOrderBy(int page,int size, String order, String seq)
			throws Exception {
		
		order = order.equals("base_duration")?"baseDuration":"baseCost";
		String hql = "from Cost order by "+order+" "+seq;
		return findByPage(page, size, hql, null);
		
	}

	public int getPageCount(int size) throws Exception {
		String hql = "select count(*) from Cost";
		return getTotalPage(size, hql, null);
	}

	public Map<String, Object> getStatusOptions() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("1", "暂停");
		map.put("0", "开通");
		return map;
	}

	public void save(Cost cost) throws Exception {
		cost.setStatus("1");
		cost.setCreateTime(new Timestamp(System.currentTimeMillis()));
		getHibernateTemplate().save(cost);
	}

	@Transactional
	public void start(int id) throws Exception {
		Cost cost = findById(id);
		cost.setStatus("0");
		cost.setStartTime(new Timestamp(System.currentTimeMillis()));
		getHibernateTemplate().update(cost);
		
	}

	public void update(Cost cost) throws Exception {
		Cost temp = findById(cost.getId());
		cost.setCreateTime(temp.getCreateTime());
		cost.setStatus(temp.getStatus());
		getHibernateTemplate().evict(temp);
		getHibernateTemplate().update(cost);
		
	}

}
